<template>
  <div class="weight-container">
    <el-card class="weight-card" shadow="hover">
      <div class="header">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon"><Setting /></el-icon>
            权重设置
            <el-tag v-if="projectData.project_name" type="primary" size="small" style="margin-left: 10px;">
              {{ projectData.project_name }}
            </el-tag>
          </h2>
          <p class="description">
            设定项目各过程的权重（用于绩效评估或评分）
            <span v-if="projectData.project_id" style="color: #e6a23c; font-weight: 500;">
              (项目编号: {{ projectData.project_id }})
            </span>
            <span v-if="projectData.project_type" style="color: #409eff; font-weight: 500; margin-left: 10px;">
              [项目类型: {{ projectData.project_type }}]
            </span>
          </p>
        </div>
        <div class="header-actions">
          <el-button  v-if="hasPermission" type="primary" @click="openDialog()" class="create-btn">
            <el-icon><Plus /></el-icon>
            添加权重
          </el-button>
          <el-button v-if="hasPermission" type="primary" @click="saveSettings" class="save-btn">
            <el-icon><Check /></el-icon>
            保存设置
          </el-button>
        </div>
      </div>

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索阶段编码、阶段说明..."
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 权重设置表格 -->
      <el-table
        :data="paginatedWeightList"
        stripe
        border
        class="weight-table"
        v-loading="loading"
        empty-text="暂无权重数据"
      >
        <el-table-column prop="phase_code" label="阶段编码" min-width="120" />
        <el-table-column prop="phase_desc" label="阶段说明" min-width="200" show-overflow-tooltip />
        <el-table-column prop="weight" label="权重设置" width="150">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.weight"
              :min="0"
              :max="100"
              :precision="0"
              :step="1"
              size="small"
              style="width: 120px"
              :disabled="!hasPermission"
              @change="handleWeightChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="currentWeight" label="当前权重" width="100">
          <template #default="scope">
            <span class="weight-value">{{ scope.row.currentWeight }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right" v-if="hasPermission">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openDialog(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button v-if="hasPermission" size="small" type="danger" @click="handleDelete(scope.row.id)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-section" v-if="filteredWeightList.length > 0">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredWeightList.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 权重统计 -->
      <div class="weight-summary">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="summary-card">
              <div class="summary-content">
                <div class="summary-title">总权重</div>
                <div class="summary-value">{{ totalWeight }}%</div>
                <div class="summary-status" :class="{ 'warning': totalWeight !== 100 }">
                  {{ totalWeight === 100 ? '权重分配合理' : '权重分配需调整' }}
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="summary-card">
              <div class="summary-content">
                <div class="summary-title">最高权重</div>
                <div class="summary-value">{{ maxWeight }}%</div>
                <div class="summary-desc">{{ maxWeightProcess }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="summary-card">
              <div class="summary-content">
                <div class="summary-title">最低权重</div>
                <div class="summary-value">{{ minWeight }}%</div>
                <div class="summary-desc">{{ minWeightProcess }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="summary-card">
              <div class="summary-content">
                <div class="summary-title">权重模板</div>
                <div class="summary-value">{{ currentWeightTemplate }}</div>
                <div class="summary-desc">{{ projectData.project_type || '建设项目' }}</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 权重分布图 -->
      <div class="weight-chart">
        <h3>权重分布图</h3>
        <div class="chart-placeholder">
          <el-icon class="chart-icon"><PieChart /></el-icon>
          <p>权重分布饼图区域</p>
          <p class="chart-desc">这里将展示各过程权重的饼图分布</p>
        </div>
      </div>
    </el-card>

    <!-- 权重创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑权重设置' : '添加权重设置'"
      width="600px"
      align-center
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目编号" prop="project_id">
              <el-input v-model="form.project_id" placeholder="项目编号" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="阶段编码" prop="phase_code">
              <el-input v-model="form.phase_code" placeholder="请输入阶段编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="阶段说明" prop="phase_desc">
          <el-input v-model="form.phase_desc" type="textarea" :rows="2" placeholder="请输入阶段说明" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权重设置" prop="weight">
              <el-input-number
                v-model="form.weight"
                :min="0"
                :max="100"
                :precision="0"
                style="width: 100%"
                placeholder="请输入权重"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注信息（选填）" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button v-if="hasPermission" type="primary" @click="handleSubmit" :loading="submitLoading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting, Check, Plus, Search, Edit, Delete, PieChart } from '@element-plus/icons-vue'
import { getProjectPhaseWeightListByProjectId, createProjectPhaseWeight, updateProjectPhaseWeight, deleteProjectPhaseWeight } from '../../api/projectPhaseWeight'

// 定义props
const props = defineProps({
  projectId: {
    type: String,
    default: ''
  },
  projectData: {
    type: Object,
    default: () => ({})
  }
})

// 获取当前登录用户信息
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))
const isAdmin = computed(() => currentUser.value.userType === '管理员')

// 检查是否为当前项目的项目经理
const isProjectManager = computed(() => {
  if (!props.projectData || !props.projectData.project_manager) {
    return false
  }
  // 检查当前用户是否为该项目的项目经理
  return currentUser.value.username === props.projectData.project_manager || 
         currentUser.value.userId === props.projectData.project_manager ||
         currentUser.value.id === props.projectData.project_manager
})

// 检查是否有权限操作（只有当前项目的项目经理可以操作）
const hasPermission = computed(() => {
  return isProjectManager.value
})

// 检查是否为管理员（只有管理员可以新增）
const canAdd = computed(() => {
  return isAdmin.value
})

// 软件项目的预定义权重数据
const softwareProjectWeights = [
  // PL1阶段 项目启动
  { phase_code: 'PL1.1', phase_desc: '公司移交', weight: 1 },
  { phase_code: 'PL1.2', phase_desc: '熟悉项目内容(含合同、方案、招投标文件)', weight: 1 },
  { phase_code: 'PL1.3', phase_desc: '预估项目成本,提出项目风险,制定项目计划', weight: 1 },
  { phase_code: 'PL1.4', phase_desc: '组建项目部(人员及硬件)', weight: 1 },
  { phase_code: 'PL1.5', phase_desc: '项目启动会', weight: 1 },
  
  // PL2阶段 深化设计
  { phase_code: 'PL2.1', phase_desc: '项目现场勘察,识别项目利益相关者,需求深入分析', weight: 5 },
  { phase_code: 'PL2.2', phase_desc: '架构设计', weight: 4 },
  { phase_code: 'PL2.3', phase_desc: '详细设计', weight: 4 },
  { phase_code: 'PL2.4', phase_desc: '制定项目实施计划,完成开工准备', weight: 2 },
  
  // PL3阶段 设备采购到货
  { phase_code: 'PL3.1', phase_desc: '落实采购单', weight: 0 },
  { phase_code: 'PL3.2', phase_desc: '确定施工分包队伍', weight: 0 },
  { phase_code: 'PL3.3', phase_desc: '设备采购(需采购部提供数据)', weight: 0 },
  { phase_code: 'PL3.4', phase_desc: '设备到货', weight: 0 },
  
  // PL4阶段 项目实施
  { phase_code: 'PL4.1', phase_desc: '开发计划', weight: 2 },
  { phase_code: 'PL4.2', phase_desc: '编写代码', weight: 10 },
  { phase_code: 'PL4.3', phase_desc: '测试计划', weight: 2 },
  { phase_code: 'PL4.4', phase_desc: '软件测试', weight: 5 },
  { phase_code: 'PL4.5', phase_desc: '部署安装', weight: 20 },
  { phase_code: 'PL4.6', phase_desc: '软件调试', weight: 10 },
  { phase_code: 'PL4.7', phase_desc: '项目全系统联合测试调试', weight: 10 },
  { phase_code: 'PL4.8', phase_desc: '项目试运行', weight: 5 },
  
  // PL5阶段 项目竣工
  { phase_code: 'PL5.1', phase_desc: '软件培训', weight: 2 },
  { phase_code: 'PL5.2', phase_desc: '竣工资料整理', weight: 5 },
  { phase_code: 'PL5.3', phase_desc: '等待验收', weight: 0 },
  { phase_code: 'PL5.4', phase_desc: '软件验收', weight: 2 },
  { phase_code: 'PL5.5', phase_desc: '质保期', weight: 5 },
  
  // PL6阶段 项目结束
  { phase_code: 'PL6.1', phase_desc: '项目审计、项目回款完成(不含质保金)', weight: 1 },
  { phase_code: 'PL6.2', phase_desc: '项目结束', weight: 1 }
]

// 工程项目的预定义权重数据（根据图片中的权重）
const engineeringProjectWeights = [
  // PL1阶段 项目启动
  { phase_code: 'PL1.1', phase_desc: '公司移交PMO', weight: 0.5 },
  { phase_code: 'PL1.2', phase_desc: '熟悉项目内容(含合同、方案、招投标文件、工程量清单)', weight: 1.5 },
  { phase_code: 'PL1.3', phase_desc: '预估项目成本,提出项目风险,制定项目计划', weight: 1 },
  { phase_code: 'PL1.4', phase_desc: '组建项目部(人员及硬件)', weight: 1 },
  { phase_code: 'PL1.5', phase_desc: '项目启动会', weight: 1 },
  
  // PL2阶段 深化设计
  { phase_code: 'PL2.1', phase_desc: '项目现场勘察,识别项目利益相关者,需求深入分析', weight: 1 },
  { phase_code: 'PL2.2', phase_desc: '深化设计', weight: 4 },
  { phase_code: 'PL2.3', phase_desc: '深化设计评审及相关工作,变更确认', weight: 1 },
  { phase_code: 'PL2.4', phase_desc: '制定项目实施计划,完成开工准备', weight: 1 },
  
  // PL3阶段 设备采购到货
  { phase_code: 'PL3.1', phase_desc: '落实采购单', weight: 2 },
  { phase_code: 'PL3.2', phase_desc: '确定施工分包队伍', weight: 2 },
  { phase_code: 'PL3.3', phase_desc: '设备采购(需采购部提供数据)', weight: 2 },
  { phase_code: 'PL3.4', phase_desc: '设备到货', weight: 3 },
  
  // PL4阶段 项目实施
  { phase_code: 'PL4.1', phase_desc: '技术交底、安全培训(含现场工程师和施工队)', weight: 1 },
  { phase_code: 'PL4.2', phase_desc: '管线敷设', weight: 8 },
  { phase_code: 'PL4.3', phase_desc: '基础安装', weight: 8 },
  { phase_code: 'PL4.4', phase_desc: '设备安装', weight: 12 },
  { phase_code: 'PL4.5', phase_desc: '设备调试', weight: 10 },
  { phase_code: 'PL4.6', phase_desc: '分系统调试', weight: 3 },
  { phase_code: 'PL4.7', phase_desc: '项目全系统联合测试调试', weight: 2 },
  { phase_code: 'PL4.8', phase_desc: '项目试运行', weight: 5 },
  
  // PL5阶段 项目竣工
  { phase_code: 'PL5.1', phase_desc: '项目培训', weight: 2 },
  { phase_code: 'PL5.2', phase_desc: '竣工资料整理', weight: 5 },
  { phase_code: 'PL5.3', phase_desc: '等待竣工验收', weight: 0 },
  { phase_code: 'PL5.4', phase_desc: '竣工验收', weight: 1 },
  { phase_code: 'PL5.5', phase_desc: '质保期', weight: 20 },
  
  // PL6阶段 项目结束
  { phase_code: 'PL6.1', phase_desc: '项目审计、项目回款完成(不含质保金)', weight: 1 },
  { phase_code: 'PL6.2', phase_desc: '项目结束', weight: 1 }
]

// 获取预定义权重数据（根据项目类型）
function getPredefinedWeights() {
  // 判断项目类型，这里需要根据实际的项目数据结构来判断
  const projectType = props.projectData.project_type || '建设项目' // 默认为建设项目
  
  console.log('当前项目类型:', projectType)
  console.log('项目数据:', props.projectData)
  
  if (projectType === '软件项目') {
    console.log('使用软件项目权重模板')
    return softwareProjectWeights
  } else {
    console.log('使用工程项目权重模板（适用于硬件项目、建设项目、其他项目）')
    return engineeringProjectWeights
  }
}

// 响应式数据
const weightList = ref([])
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const searchKeyword = ref('')
const formRef = ref()

const form = ref({
  id: null,
  project_id: '',
  phase_code: '',
  phase_desc: '',
  weight: 0,
  remark: ''
})

const formRules = {
  project_id: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
  phase_code: [{ required: true, message: '请输入阶段编码', trigger: 'blur' }],
  phase_desc: [{ required: true, message: '请输入阶段说明', trigger: 'blur' }],
  weight: [{ required: true, message: '请输入权重', trigger: 'blur' }]
}

// 分页数据
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 过滤后的权重列表
const filteredWeightList = computed(() => {
 // const currentProjectId = props.projectData.project_id || props.projectId
  
  let filtered = weightList.value;
   
  return filtered
})

// 分页后的权重列表
const paginatedWeightList = computed(() => {
  const start = (pagination.value.page - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return filteredWeightList.value.slice(start, end)
})

// 计算总权重
const totalWeight = computed(() => {
  return filteredWeightList.value.reduce((sum, item) => sum + (parseInt(item.weight) || 0), 0)
})

// 计算最高权重
const maxWeight = computed(() => {
  if (filteredWeightList.value.length === 0) return 0
  return Math.max(...filteredWeightList.value.map(item => parseInt(item.weight) || 0))
})

// 计算最低权重
const minWeight = computed(() => {
  if (filteredWeightList.value.length === 0) return 0
  return Math.min(...filteredWeightList.value.map(item => parseInt(item.weight) || 0))
})

// 最高权重过程
const maxWeightProcess = computed(() => {
  const maxItem = filteredWeightList.value.find(item => parseInt(item.weight) === maxWeight.value)
  return maxItem ? maxItem.phase_desc : ''
})

// 最低权重过程
const minWeightProcess = computed(() => {
  const minItem = filteredWeightList.value.find(item => parseInt(item.weight) === minWeight.value)
  return minItem ? minItem.phase_desc : ''
})

// 当前使用的权重模板类型
const currentWeightTemplate = computed(() => {
  const projectType = props.projectData.project_type || '建设项目'
  return projectType === '软件项目' ? '软件项目模板' : '工程项目模板'
})

// 获取状态标签样式
function getStatusTagType(status) {
  const statusMap = {
    '已设置': 'success',
    '未设置': 'info',
    '待调整': 'warning'
  }
  return statusMap[status] || 'info'
}

// 生成32位GUID
function generateGUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  }).replace(/-/g, '')
}

// 自动生成默认权重数据
async function generateDefaultWeights() {
  const currentProjectId = props.projectData.project_id || props.projectId
  if (!currentProjectId) return
  
  try {
    // 检查是否已有权重数据
    const res = await getProjectPhaseWeightListByProjectId(currentProjectId)
    const existingWeights = Array.isArray(res) ? res : []
    
    // 过滤当前项目的数据
    const currentProjectWeights = existingWeights.filter(item => item.project_id === currentProjectId)
    console.log('当前项目已有权重数量:', currentProjectWeights.length)
    
    // 找出缺失的权重项（检查项目编号+阶段编码是否已存在）
    const missingWeights = []
    const predefinedWeights = getPredefinedWeights()
    for (const weight of predefinedWeights) {
      // 检查该阶段编码是否已存在
      const existingWeight = currentProjectWeights.find(item => 
        item.phase_code === weight.phase_code
      )
      if (!existingWeight) {
        missingWeights.push(weight)
      }
    }
    
    if (missingWeights.length === 0) {
      console.log('所有权重项都已存在，跳过自动生成')
      return
    }
    
    // 计算已有权重总和
    const existingWeightSum = currentProjectWeights.reduce((sum, item) => sum + (parseInt(item.weight) || 0), 0)
    console.log('已有权重总和:', existingWeightSum)
    
    // 计算需要分配的权重
    const remainingWeight = 100 - existingWeightSum
    console.log('需要分配的权重:', remainingWeight)
    
    if (remainingWeight <= 0) {
      console.log('权重已满100%，无需生成新权重')
      return
    }
    
    // 自动分配权重
    const defaultWeightList = []
    const weightPerItem = Math.floor(remainingWeight / missingWeights.length)
    const extraWeight = remainingWeight % missingWeights.length
    
    missingWeights.forEach((weight, index) => {
      let assignedWeight = weightPerItem
      // 将余数分配给前几个项目
      if (index < extraWeight) {
        assignedWeight += 1
      }
      
      defaultWeightList.push({
        id: generateGUID(),
        project_id: currentProjectId,
        phase_code: weight.phase_code,
        phase_desc: weight.phase_desc,
        weight: assignedWeight,
        remark: '系统自动生成'
      })
    })
    
    // 批量创建权重
    let successCount = 0
    for (const weight of defaultWeightList) {
      try {
        await createProjectPhaseWeight(weight)
        successCount++
        console.log(`创建权重: ${weight.phase_code}, 权重: ${weight.weight}`)
      } catch (error) {
        console.error(`创建权重失败: ${weight.phase_code}`, error)
      }
    }
    
    if (successCount > 0) {
      ElMessage.success(`已自动生成${successCount}个缺失的项目权重，总权重达到100%`)
    }
    console.log('默认权重数据生成完成')
  } catch (error) {
    console.error('生成默认权重数据失败:', error)
  }
}

// 打开对话框
function openDialog(weight = null) {
  if (weight) {
    form.value = { ...weight }
  } else {
    form.value = {
      id: null,
      project_id: props.projectData.project_id || props.projectId || '',
      phase_code: '',
      phase_desc: '',
      weight: 0,
      remark: ''
    }
  }
  dialogVisible.value = true
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate(async (valid) => {
      if (!valid) return
      
      submitLoading.value = true
      
      if (!form.value.id) {
        const payload = { ...form.value }
        payload.id = generateGUID()
        console.log('创建权重设置，payload:', payload)
        await createProjectPhaseWeight(payload)
        ElMessage.success('权重设置添加成功')
      } else {
        console.log('更新权重设置，payload:', form.value)
        await updateProjectPhaseWeight(form.value.id, form.value)
        ElMessage.success('权重设置更新成功')
      }
      
      dialogVisible.value = false
      loadProjectPhaseWeight()
    })
  } catch (error) {
    ElMessage.error('操作失败，请重试')
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 删除权重设置
function handleDelete(id) {
  ElMessageBox.confirm('确认删除该权重设置？此操作不可恢复', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteProjectPhaseWeight(id)
      ElMessage.success('删除成功')
      loadProjectPhaseWeight()
    } catch (error) {
      ElMessage.error('删除失败，请重试')
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

// 分页大小改变
function handleSizeChange(size) {
  pagination.value.pageSize = size
  pagination.value.page = 1
  console.log('分页大小改变:', size, '当前页:', pagination.value.page)
}

// 当前页改变
function handleCurrentChange(page) {
  pagination.value.page = page
  console.log('当前页改变:', page)
}

// 权重变化处理
function handleWeightChange(row) {
  // 确保权重是数字类型
  row.weight = parseInt(row.weight) || 0
  console.log('权重变化:', row.phase_code, '新权重:', row.weight)
}

// 保存设置
async function saveSettings() {
  if (totalWeight.value !== 100) {
    ElMessage.warning('权重总和必须为100%，请调整后再保存')
    return
  }
  
  try {
    // 更新当前权重
    for (const item of weightList.value) {
      item.currentWeight = item.weight
      item.status = '已设置'
      await updateProjectPhaseWeight(item.id, item)
    }
    
    // 重新加载权重数据以确保数据同步
    await loadProjectPhaseWeight()
    
    ElMessage.success('权重设置保存成功')
  } catch (error) {
    console.error('保存权重设置失败:', error)
    ElMessage.error('保存权重设置失败，请重试')
  }
}

// 加载项目权重列表
async function loadProjectPhaseWeight() {
  loading.value = true
  try {
    const currentProjectId = props.projectData.project_id || props.projectId
    
    if (currentProjectId) {
      console.log('加载项目权重，项目ID:', currentProjectId)
      
      const res = await getProjectPhaseWeightListByProjectId(currentProjectId)
      const allWeight = Array.isArray(res) ? res : []
      
      // 过滤当前项目的数据并确保权重是数字类型
      weightList.value = allWeight.filter(item => item.project_id === currentProjectId).map(item => ({
        ...item,
        weight: parseInt(item.weight) || 0,
        currentWeight: parseInt(item.weight) || 0
      }))
      console.log('当前项目权重数量:', weightList.value.length)
      console.log('权重数据:', weightList.value)
      
      // 检查是否需要生成默认权重数据
      const existingPhaseCodes = weightList.value.map(weight => weight.phase_code)
      const predefinedWeights = getPredefinedWeights()
      const missingPhaseCodes = predefinedWeights.filter(weight => !existingPhaseCodes.includes(weight.phase_code))
      
      if (missingPhaseCodes.length > 0) {
        console.log('发现缺失的权重项，开始生成默认权重数据，缺失项:', missingPhaseCodes.length)
        // 生成默认权重数据
        await generateDefaultWeights()
        // 重新加载数据
        const newRes = await getProjectPhaseWeightListByProjectId(currentProjectId)
        const newAllWeight = Array.isArray(newRes) ? newRes : []
        weightList.value = newAllWeight.filter(item => item.project_id === currentProjectId)
        console.log('生成默认权重后，当前项目权重数量:', weightList.value.length)
        console.log('重新加载后的权重数据:', weightList.value)
      } else {
        console.log('所有权重项都已存在，无需生成默认权重数据')
      }
    } else {
      weightList.value = []
      console.log('没有项目编号，不加载项目权重')
    }
  } catch (error) {
    ElMessage.error('加载项目权重失败')
    console.error('加载项目权重失败:', error)
    weightList.value = []
  } finally {
    loading.value = false
  }
}

// 监听项目数据变化
watch(() => props.projectData, (newProjectData) => {
  if (newProjectData && newProjectData.project_id) {
    if (dialogVisible.value && !form.value.project_id) {
      form.value.project_id = newProjectData.project_id
    }
    loadProjectPhaseWeight()
  }
}, { deep: true })

// 监听项目ID变化
watch(() => props.projectId, (newProjectId) => {
  if (newProjectId) {
    console.log('项目ID变化，重新加载项目权重:', newProjectId)
    loadProjectPhaseWeight()
  }
})

onMounted(() => {
  try {
    loadProjectPhaseWeight()
  } catch (error) {
    console.error('项目权重页面初始化失败:', error)
  }
})
</script>

<style scoped>
.weight-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.weight-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  flex: 1;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 24px;
  color: #909399;
}

.description {
  margin: 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
}

.create-btn, .save-btn {
  padding: 12px 20px;
  font-weight: 500;
  border-radius: 8px;
}

.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.weight-table {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.pagination-section {
  margin-bottom: 30px;
  display: flex;
  justify-content: center;
}

.weight-value {
  font-weight: 600;
  color: #409eff;
}

.weight-summary {
  margin-bottom: 30px;
}

.summary-card {
  text-align: center;
  border-radius: 8px;
}

.summary-content {
  padding: 20px;
}

.summary-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.summary-status {
  font-size: 12px;
  color: #67c23a;
}

.summary-status.warning {
  color: #e6a23c;
}

.summary-desc {
  font-size: 12px;
  color: #909399;
}

.weight-chart {
  margin-top: 30px;
}

.weight-chart h3 {
  margin-bottom: 16px;
  color: #303133;
}

.chart-placeholder {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  height: 300px;
  background: #fafafa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.chart-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.chart-desc {
  font-size: 14px;
  margin-top: 8px;
  text-align: center;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
  font-weight: 600;
}
</style> 